#include <QLineEdit>
#include "line-edit-delegate.h"

LineEditDelegate::LineEditDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}

QWidget* LineEditDelegate::createEditor (QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);
    QLineEdit* lineEdit = new QLineEdit(parent);
    lineEdit->setText(m_defaultText);
    return lineEdit;
}

void LineEditDelegate::setEditorData (QWidget* editor, const QModelIndex& index) const
{
    QString text = index.data(Qt::UserRole).toString();
    m_oldText = text;

    QLineEdit* lineEdit = static_cast<QLineEdit*>(editor);
    lineEdit->setText(text);
}

void LineEditDelegate::setModelData (QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    QLineEdit* lineEdit = static_cast<QLineEdit*>(editor);

    QString newText = lineEdit->text();
    if (newText == m_oldText)
        return;

    model->setData(index, newText, Qt::UserRole);
}

void LineEditDelegate::setDefaultText(QString text)
{
    m_defaultText = text;
}
